﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Net;
using System.Security.Claims;
using Volo.Abp.Domain.Repositories;
using SmartHotel.Domain;
namespace SmartHotel
{
    public class CustomerAuthoorzationFilterAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        public async void OnAuthorization(AuthorizationFilterContext context)
        {
            string DosplayName = context.ActionDescriptor.DisplayName;
            //获取接口地址
            string AttributeRouteInfo = context.ActionDescriptor.AttributeRouteInfo.Template;
            ControllerActionDescriptor descriptor=context.ActionDescriptor as ControllerActionDescriptor;
            string ControllerName = descriptor.ControllerName;
            string ActionName = descriptor.ActionName;

            if (!context.ActionDescriptor.EndpointMetadata.Any(em => em is Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute))
            { 
                bool IsLogin=context.HttpContext.User.Identity.IsAuthenticated;
                if (!IsLogin)
                {
                    context.Result = new StatusCodeResult((int)HttpStatusCode.Unauthorized);
                }
                else
                {
                    if (!context.ActionDescriptor.EndpointMetadata.Any(em => em is IAuthorizationFilter))
                    {
                        IServiceProvider serviceProvider = context.HttpContext.RequestServices;
                        var menuRepository = serviceProvider.GetService<IRepository<MenuTable>>();
                        var RoleRepository = serviceProvider.GetService<IRepository<RoleTable>>();
                        var roleMenuRepository = serviceProvider.GetService<IRepository<RoleMenu>>();

                        var menuIdList = await menuRepository.GetQueryableAsync();
                        var menuroleIdList = await roleMenuRepository.GetQueryableAsync();

                        var rolemenuId = menuroleIdList.Where(x => menuIdList.Where(m => m.MenuInterface == AttributeRouteInfo).Select(s => s.Id).Contains(x.Id)).Select(m => m.Id).ToList();
                        string UserName = context.HttpContext.User.Identity.Name;
                        var claims = context.HttpContext.User.Claims;

                        int[] roleid = claims.First(m => m.Type == ClaimTypes.Role).Value.Split(',')
                            .Select(m => Convert.ToInt32(m)).ToArray();

                        if (!roleid.Any(m => rolemenuId.Contains(m)))
                        {
                            context.Result = new StatusCodeResult((int)HttpStatusCode.Forbidden);
                        }
                    }
                }
            }
        }
    }
}
